package com.laomuji.android.mvvm.http

import com.laomuji.android.mvvm.http.common.GsonManager
import com.laomuji.android.mvvm.http.interceptor.StandardInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Retrofit工厂
 * @author laomuji666
 * @since 2024/2/20
 */
class RetrofitServiceFactory<T>(cls: Class<T>, baseUrl: String, tag: String) {

    //超时时间
    private val _timeout: Long = 30 * 1000

    //service对象
    private val _service: T

    //拦截器
    private val standardInterceptor: StandardInterceptor = StandardInterceptor(tag)

    /**
     * 创建Retrofit的Service对象
     */
    init {
        //创建HttpClient
        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
        builder.retryOnConnectionFailure(true)
        builder.connectTimeout(_timeout, TimeUnit.SECONDS)
        builder.writeTimeout(_timeout, TimeUnit.SECONDS)
        builder.readTimeout(_timeout, TimeUnit.SECONDS)

        //添加拦截器
        builder.addInterceptor(standardInterceptor)

        //创建Retrofit
        _service = Retrofit.Builder()
            .client(builder.build())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(GsonManager.gson))
            .baseUrl(baseUrl)
            .build().create(cls)
    }

    /**
     * 获取service对象
     */
    fun getService(): T = _service

    /**
     * 添加请求头
     */
    fun addHeader(key: String, value: String) =
        standardInterceptor.headerInterceptor.addHeader(key, value)
}